<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>年轮家族管理系统</h2>
        <p>请登录您的账户</p>
      </div>
      
      <a-form 
        :model="loginForm" 
        :rules="loginRules"
        class="login-form"
        @finish="handleLogin"
      >
        <a-form-item name="username">
          <a-input
            v-model:value="loginForm.username"
            placeholder="请输入用户名"
            size="large"
          >
            <template #prefix>
              <UserOutlined />
            </template>
          </a-input>
        </a-form-item>
        
        <a-form-item name="password">
          <a-input-password
            v-model:value="loginForm.password"
            placeholder="请输入密码"
            size="large"
            @pressEnter="handleLogin"
          >
            <template #prefix>
              <LockOutlined />
            </template>
          </a-input-password>
        </a-form-item>
        
        <a-form-item>
          <a-button
            type="primary"
            size="large"
            block
            :loading="loading"
            html-type="submit"
          >
            {{ loading ? '登录中...' : '登录' }}
          </a-button>
        </a-form-item>
      </a-form>
      
      <div class="login-footer">
        <p>年轮 (Annual Ring) - 族谱管理系统 ©2025</p>
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { useUserStore } from '@/stores/user'
import { useMutation } from '@tanstack/vue-query'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
import api from '../api'

export default {
  name: 'Login',
  components: {
    UserOutlined,
    LockOutlined
  },
  setup() {
    const router = useRouter()
    const userStore = useUserStore()
    const loading = ref(false)
    const loginForm = ref({
      username: 'admin',
      password: 'Admin@123'
    })
    
    // 登录的 useMutation 配置
    const { mutateAsync: loginMutation } = useMutation({
      mutationFn: (credentials) => api.post('/auth/login', credentials),
      onSuccess: (result) => {
        if (result.data.code === 200) {
          // 假设后端返回包含 access_token 和 refresh_token 的对象
          const { access_token, refresh_token } = result.data.data
          userStore.setTokens(access_token, refresh_token)
        }
      }
    })
    
    // 获取用户信息的 useMutation 配置
    const { mutateAsync: fetchUserInfoMutation } = useMutation({
      mutationFn: () => api.get('/auth/info'),
      onSuccess: (result) => {
        if (result.data.code === 200) {
          userStore.setUser(result.data.data)
        }
      }
    })
    
    const loginRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
      ]
    }
    
    const handleLogin = async () => {
      loading.value = true
      
      try {
        const response = await loginMutation(loginForm.value)
        
        if (response?.data?.code === 200) {
          message.success('登录成功')
          // 获取用户信息
          await fetchUserInfoMutation()
          // 跳转到仪表盘
          router.push('/dashboard')
        } else {
          message.error(response?.data?.msg || '登录失败')
        }
      } catch (err) {
        console.error('登录错误:', err)
        message.error('登录失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
    
    return {
      loginForm: loginForm.value,
      loginRules,
      loading: loading.value,
      handleLogin,
      UserOutlined,
      LockOutlined
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-box {
  width: 100%;
  max-width: 400px;
  padding: 40px 30px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.login-header h2 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 24px;
}

.login-header p {
  margin: 0 0 30px 0;
  color: #666;
}

.login-form {
  margin-bottom: 30px;
}

.login-footer {
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.login-footer p {
  margin: 0;
  color: #999;
  font-size: 12px;
}
</style>